<?php

namespace app\v1\controller;

use support\Request;
use app\model\VipOrderModel;
use app\model\UserModel;
use Exception;
use app\model\VipSolutionModel;
use EasyWeChat\Factory;
use support\Log;
use app\model\VipDetailModel;
use app\model\Util;

class VipController
{
    /**
     * 获取VIP套餐信息
     * @param \support\Request $request
     * @return mixed
     */
    public function packages(Request $request)
    {
        try {
            // VIP套餐配置
            $packages = [];

            $data = VipSolutionModel::where('status', '=','online')->get();
            foreach ($data as $item) {
                $packages[] = [
                    'id' => $item->id,
                    'name' => $item->name,
                    'price' => $item->money,
                    'duration' => $item->days,
                    'description' => $item->description,
                    'image' => Util::pathToUrl($item->image),
                ];
            }

            // 获取VIP权益列表
            $rights = [];
            $vipRights = VipDetailModel::get();
            foreach ($vipRights as $right) {
                $rights[] = [
                    'id' => $right->id,
                    'name' => $right->name,
                    'sub_name' => $right->sub_name,
                    'icon' => Util::pathToUrl($right->icon),
                    'description' => $right->description,
                ];
            }

            return json([
                'data' => [
                    'packages' => $packages,
                    'rights' => $rights
                ],
                'msg' => '获取VIP套餐成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取用户VIP状态
     * @param \support\Request $request
     * @return mixed
     */
    public function status(Request $request)
    {
        try {
            $user = $request->userLogin;

            if (!$user) {
                throw new Exception('用户未登录');
            }

            $isVip = false;
            $vipExpireTime = null;

            if ($user->vip_at && $user->vip_at > time()) {
                $isVip = true;
                $vipExpireTime = $user->vip_at;
            }

            return json([
                'data' => [
                    'is_vip' => $isVip,
                    'vip_expire_time' => $vipExpireTime,
                    'current_time' => time(),
                    'expire_time'=>($user->vip_at - time())*1000
                ],
                'msg' => '获取VIP状态成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 创建VIP订单
     * @param \support\Request $request
     * @return mixed
     */
    public function createOrder(Request $request)
    {
        try {
            $user = $request->userLogin;

            if (!$user) {
                throw new Exception('用户未登录');
            }

            if (!$user->phone) {
                throw new Exception('请先绑定手机号');
            }

            $input = $request->post('data');
            $packageId = $input['package_id'];
            if (!$packageId) {
                throw new Exception('请选择VIP套餐');
            }

            $package = VipSolutionModel::find($packageId);
            // 生成订单号
            $orderNo = 'VIP' . date('YmdHis') . rand(1000, 9999);

            // 创建VIP订单
            $vipOrder = new VipOrderModel();
            $vipOrder->user_id = $user->id;
            $vipOrder->order_no = $orderNo;
            $vipOrder->money = $package->money;
            $vipOrder->status = 'unpay';
            $vipOrder->created_at = time();
            $vipOrder->updated_at = time();
            $vipOrder->solution_id = $packageId;
            $vipOrder->save();

            // 下单
            // 生成微信支付订单
            $outTradeNo = 'vip-' . $vipOrder->id . '-' . rand(100000, 999999);
                    
            // 获取微信支付配置
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            $jssdk = $payment->jssdk;

            $result = $payment->order->unify([
                'body' => $package->name,
                'out_trade_no' => $outTradeNo,
                'total_fee' => (int)($vipOrder->money * 100), // 转换为分
                'notify_url' => config('site.site_url') . "/v1/vip/notify",
                'trade_type' => 'JSAPI',
                'openid' => $user['open_id'],
            ]);

            Log::info('pay-result',['result'=>$result]);

            if ($result['return_code'] !== 'SUCCESS' || $result['result_code'] !== 'SUCCESS') {
                throw new Exception('微信支付订单创建失败：' . ($result['err_code_des'] ?? '未知错误'));
            }

            $config = $jssdk->bridgeConfig($result['prepay_id'], false);

            return json([
                'data' => [
                    'order_id' => $vipOrder->id,
                    'order_no' => $vipOrder->order_no,
                    'money' => $vipOrder->money,
                    'package_name' => $package->name,
                    'config' => $config
                ],
                'msg' => '创建VIP订单成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function notify(Request $request) {
        try {
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            
            $response = $payment->handlePaidNotify(function ($message, $fail) {
                // 查询支付记录
                $outTradeNo = $message['out_trade_no'];
                $oId = (int)explode('-', $outTradeNo)[1];
                
                $payRecord = VipOrderModel::find($oId);
                if (!$payRecord) {
                    return $fail('支付记录不存在');
                }

                $this->payOrder($oId);

                return true;
            });

            return $response;
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    protected function payOrder($orderId)
    {
        try {
            // 查找订单
            $vipOrder = VipOrderModel::find($orderId);

            if (!$vipOrder) {
                throw new Exception('订单不存在');
            }

            if ($vipOrder->status !== 'unpay') {
                throw new Exception('订单状态异常');
            }

            // 更新订单状态为已支付
            $vipOrder->status = 'pay';
            $vipOrder->updated_at = time();
            $vipOrder->save();

            // 更新用户VIP过期时间
            $user = UserModel::find($vipOrder->user_id);
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $currentVipAt = $user->vip_at ?: time();
            $solution = VipSolutionModel::find($vipOrder->solution_id);
            if (!$solution) {
                throw new Exception('套餐不存在');
            }

            // 根据订单金额判断套餐类型
            $duration = $solution->days * 24 * 3600;

            $newVipAt = max($currentVipAt, time()) + $duration;

            $user->vip_at = $newVipAt;
            $user->updated_at = time();
            $user->save();

            return json([
                'data' => [
                    'order_id' => $vipOrder->id,
                    'vip_expire_time' => $newVipAt
                ],
                'msg' => '支付成功，VIP已开通',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    protected function getVipSolution(){

        $data = VipSolutionModel::where('status', '=','online')->get();
        $packages = [];
        foreach ($data as $item) {
            $packages[$item->id] = [
                'id' => $item->id,
                'name' => $item->name,
                'price' => $item->money,
                'duration' => $item->days,
                'description' => $item->description
            ];
        }

        return $packages;
    }

    public function recentOrders(Request $request)
    {
        try {
            $data = VipOrderModel::where('status', '=', 'pay')
                ->limit(10)->get();

            $orders = [];    
            foreach($data as $o){
                $user = UserModel::find($o->user_id);
                $solution = VipSolutionModel::find($o->solution_id);
                $orders[] = human_time($o->created_at)." ".$user->safePhone()."购买了{$solution->name}";
            }    

            return json([
                'data' => $orders,
                'msg' => '获取最近订单记录成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 